const ava = require('ava');
const http = require('http');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const fetch = require('../lib/fetch');
const url = require('url');
const phax = require('..');
let server;
const BASEURL = 'http://127.0.0.1:3000/a';
ava.before(t => {
  const app = new Koa();
  app.use(bodyParser()); // 参数解析
  app.use(async (ctx, next) => {
    let method = ctx.method;
    let params = method === 'GET' ? ctx.query : ctx.request.body;
    let res;
    if (params.accept === 'text') {
      res = 'SUCCESS';
    }
    else {
      params.method = method;
      res = params;
    }
    if (params.status !== '404') {
      ctx.body = res;
    }
    else {
      await next();
    }
  });
  server = http.createServer(app.callback());
  server.listen(3000);
});
ava('get_status404', async (t) => {
  t.plan(1);
  let res = await fetch(BASEURL + '?status=404').then(res => res.status);
  t.is(res, 404);
});
ava('get_text', async (t) => {
  t.plan(1);
  let res = await fetch(BASEURL + '?accept=text').then(res => res.text());
  t.is(res, 'SUCCESS');
});
ava('get', async (t) => {
  t.plan(2);
  let res = await fetch(BASEURL + '?key=param').then(res => res.json());
  t.is(res.method, 'GET');
  t.is(res.key, 'param');
});
ava('get_params', async (t) => {
  t.plan(2);
  let res = await fetch(BASEURL, {
    body: { key: 'param' }
  }).then(res => res.json());
  t.is(res.method, 'GET');
  t.is(res.key, 'param');
});
ava('post', async (t) => {
  t.plan(1);
  let res = await fetch(BASEURL, {
    method: 'post'
  }).then(res => res.json());
  t.is(res.method, 'POST');
});
ava('post_url_param', async (t) => {
  t.plan(2);
  let urlParams = new url.URLSearchParams();
  urlParams.append('key', 'param');
  let res = await fetch(BASEURL, {
    method: 'post',
    body: urlParams
  }).then(res => res.json());
  t.is(res.method, 'POST');
  t.is(res.key, 'param');
});
ava('post_json', async (t) => {
  t.plan(2);
  let param = { key: 'param' };
  let res = await fetch(BASEURL, {
    method: 'post',
    body: JSON.stringify(param),
    headers: {
      'content-type': 'application/json'
    }
  }).then(res => res.json());
  t.is(res.method, 'POST');
  t.is(res.key, 'param');
});
ava('phax_get', async (t) => {
  t.plan(1);
  let res = await phax(BASEURL);
  t.is(res.method, 'GET');
});
ava('phax_get_text', async (t) => {
  t.plan(1);
  let res = await phax(BASEURL, { body: { accept: 'text' }});
  t.is(res, 'SUCCESS');
});
ava('phax_post_json', async (t) => {
  t.plan(2);
  let res = await phax(BASEURL, { json: { key: 'param' }, method: 'POST' });
  t.is(res.method, 'POST');
  t.is(res.key, 'param');
});
ava.after(t => {
  server.close();
});
